<template>
  <el-card>
    <template #header>
      <div class="header">
        <div class="search">
          <el-input
            style="width: 200px; margin-right: 10px"
            placeholder="商品名称"
            v-model="params.title"
            @change="queryTitle"
            :clearable="true"
          />
          <el-select class="m-2" placeholder="全部商品"
            v-model="params.isdown"
            @change="queryIsDown"
            :clearable="true">
            <el-option v-for="item in [
                {value: 1, label: '在售中'},
                {value: 2, label: '已下架'}
              ]"
              :key="item.value"
              :label="item.label"
              :value="item.value"></el-option>
          </el-select>
        </div>
        <el-button-group class="good-btn-group">
          <el-popconfirm title="确定要上架吗？"
            cancel-button-text="否"
            confirm-button-text="是"
            @confirm="batch(1)">
            <template #reference>
              <el-button type="success">批量上架</el-button>
            </template>
          </el-popconfirm>
          <el-popconfirm title="确定要下架吗？"
            cancel-button-text="否"
            confirm-button-text="是"
            @confirm="batch(2)">
            <template #reference>
              <el-button type="danger">批量下架</el-button>
            </template>
          </el-popconfirm>
        </el-button-group>
      </div>
    </template>
    <el-table class="table-row-optimize"
      v-loading="state.loading"
      ref="multipleTable"
      :data="state.tableData"
      tooltip-effect="dark"
      style="width: 100%"
      @selection-change="selectionChangeIds">
      <el-table-column type="selection" width="50" align="center">
      </el-table-column>
      <el-table-column prop="id" label="#ID" align="center" width="60"/>
      <el-table-column v-viewer label="" width="120" align="center">
        <template #default="scope">
          <img :key="scope.row.id"
            @click="preview(scope.row)"
            :src="scope.row.master" width="90" height="48"
            style="min-height: 48px; border: 1px solid rgb(228,228,228);border-radius: 5px;" :alt="scope.row.title"/>
        </template>
      </el-table-column>
      <el-table-column prop="title" width="320" label="商品信息">
        <template #default="scope">
          <el-tag type="success" v-if="scope.row.isdown === 1">在售中</el-tag>
          <el-tag type="danger" v-else>已下架</el-tag>
          {{ scope.row.title }}
        </template>
      </el-table-column>
      <el-table-column prop="price" label="售价" align="center">
        <template #default="scope">
          <el-tag type="danger">{{ scope.row.price }} / {{ scope.row.units }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="cost_price" label="成本价" align="center">
        <template #default="scope">
          <el-tag type="danger">{{ scope.row.cost_price }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="stock" label="库存" align="center"/>
      <el-table-column prop="sales" label="本月销量" align="center" width="100"/>

      <el-table-column label="上架时间" align="center" width="120">
        <template #default="scope">
          {{ toDateTime(scope.row.created_at) }}
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" width="140">
        <template #default="scope">
          <el-popconfirm title="确定要下架吗？"
            cancel-button-text="否"
            confirm-button-text="是"
            v-if="scope.row.isdown === 1"
            @confirm="updatus(scope.row)">
            <template #reference>
              <el-button size="small" type="danger">下架</el-button>
            </template>
          </el-popconfirm>

          <el-popconfirm title="确定要上架吗？"
            cancel-button-text="否"
            confirm-button-text="是"
            v-if="scope.row.isdown === 2"
            @confirm="updatus(scope.row)">
            <template #reference>
              <el-button size="small" type="success">上架</el-button>
            </template>
          </el-popconfirm>

          <el-button size="small" type="primary" style="margin-left: 10px;" @click="updated(scope.row)">修改</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--总数超过一页，再展示分页器-->
    <el-pagination
      background
      layout="prev, pager, next, jumper, total"
      :total="state.total"
      :page-size="params.limit"
      :current-page="params.page"
      @current-change="changePage"
    />
  </el-card>

  <!-- 新增、编辑 -->
  <DialogGoods ref="refGoods" :reload="getList"/>

  <!-- Image Preview -->
  <viewer :images="images">
    <img v-for="src in images" :key="src" :src="src">
  </viewer>
</template>

<script setup>
import { toDateTime } from "../utils";
import { getCurrentInstance, onMounted, reactive, ref } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { AdminGoodsList, AdminGoodsPostOnlyStatus } from "../api/server/goods";
import DialogGoods from "../components/DialogGoods.vue";

const { proxy } = getCurrentInstance()
const router = useRouter()
const images = ref([])
const refGoods = ref(null)
const state = reactive({
  loading: true,
  tableData: null,
  checkIds: [],
  total: 0,
})
const params = reactive({
  page: 1,
  limit: 10,
  title: '',
  ishot: '',
  isdown: '',
})

onMounted(() => {
  params.ishot = router.currentRoute.value.query.ishot || ''
  getList()
})
const getList = async (page) => {
  page && (params.page = page)
  state.loading = true
  const { data, total, current_page } = await AdminGoodsList(params)
  state.tableData = data
  state.total = total
  params.page = current_page
  state.loading = false
}

const preview = (row) => proxy.$viewerApi({ images: [row.master] })
const queryTitle = () => getList()
const queryIsDown = () => getList()
const selectionChangeIds = row => state.checkedIds = row
const changePage = (page) => getList(page)
const updated = row => refGoods.value.show(+row.id)

/**
 * 更新单个商品上下架状态
 */
const updatus = async row => {
  await AdminGoodsPostOnlyStatus(row.id, { isdown: row.isdown === 1 ? 2 : 1 })
  ElMessage.success(row.isdown === 1 ? '商品已下架' : '商品已上架')
  await getList()
}

/**
 * 批量更新多个商品上架(1), 下架(0)
 */
const batch = async (isdown) => {
  if (!state.checkedIds || state.checkedIds.length === 0) {
    ElMessage.error('请选择要操作的数据')
    return false
  }
  const ids = state.checkedIds.map(e => e.id)

  await AdminGoodsPostOnlyStatus(ids, { isdown })
  ElMessage.success('操作成功')
  await getList()
}
</script>


<style scoped>

.good-container {
  min-height: 100%;
}

.el-card.is-always-shadow {
  min-height: 100% !important;
  box-shadow: 0 0 0 0;
}

.el-button + .el-button {
  margin-left: 0px;
}

.operate-btn {
  margin-left: 10px;
  cursor: pointer;
}
</style>
<style>

.good-container .el-card__body {
  padding: 0 !important;
}

.el-link + .el-link {
  margin-left: 10px;
}
</style>
